'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
  const { user_id, opponent_id, mode } = event;
  try {
    const userCollection = db.collection('users');
    const pkCollection = db.collection('pk_records');

    // 验证用户
    const userRes = await userCollection.where({ _id: user_id }).get();
    if (!userRes.data.length) {
      return { code: -1, msg: '用户不存在' };
    }
    const user = userRes.data[0];

    let opponent, pk_id;

    if (mode === 'specific') {
      if (!opponent_id) {
        return { code: -1, msg: '请提供对手ID或用户名' };
      }
      // 按 _id 或 name 查询对手
      const opponentRes = await userCollection
        .where(dbCmd.or([
          { _id: opponent_id },
          { name: opponent_id }
        ]))
        .get();
      if (!opponentRes.data.length) {
        console.warn(`对手查询失败: opponent_id=${opponent_id}`);
        return { code: -1, msg: '对手不存在' };
      }
      opponent = opponentRes.data[0];

      if (opponent._id === user_id) {
        return { code: -1, msg: '不能挑战自己' };
      }

      const pkRes = await pkCollection.add({
        challenger_id: user_id,
        opponent_id: opponent._id,
        status: 'pending',
        questions: [],
        challenger_answers: [],
        opponent_answers: [],
        challenger_score: 0,
        opponent_score: 0,
        created_at: new Date()
      });
      pk_id = pkRes.id;
    } else {
      // 清理过期 pending 记录
      await pkCollection
        .where({
          status: 'pending',
          created_at: dbCmd.lt(new Date(Date.now() - 30000))
        })
        .update({ status: 'cancelled' });

      const matchRes = await pkCollection
        .where({
          status: 'pending',
          challenger_id: dbCmd.neq(user_id),
          created_at: dbCmd.gte(new Date(Date.now() - 30000))
        })
        .orderBy('created_at', 'asc')
        .limit(1)
        .get();

      if (matchRes.data.length) {
        const existingPk = matchRes.data[0];
        opponent = (await userCollection.where({ _id: existingPk.challenger_id }).get()).data[0];
        pk_id = existingPk._id;

        await pkCollection.doc(pk_id).update({
          opponent_id: user_id,
          status: 'accepted',
          questions: (await db.collection('questions').aggregate().sample({ size: 10 }).end()).data
        });
      } else {
        const pkRes = await pkCollection.add({
          challenger_id: user_id,
          opponent_id: null,
          status: 'pending',
          questions: [],
          challenger_answers: [],
          opponent_answers: [],
          challenger_score: 0,
          opponent_score: 0,
          created_at: new Date()
        });
        pk_id = pkRes.id;
        opponent = { name: '等待匹配', _id: null };
      }
    }

    return {
      code: 0,
      data: { pk_id, opponent: { name: opponent.name || '未知', id: opponent._id } },
      msg: mode === 'specific' ? '挑战发起成功' : '匹配发起成功'
    };
  } catch (e) {
    console.error('发起PK失败:', e);
    return { code: -1, msg: `发起PK失败: ${e.message || '未知错误'}` };
  }
};